import router from "@/router";
import store from "@/store";
import NProgress from "nprogress"; // 引入一份进度条插件
import "nprogress/nprogress.css"; // 引入进度条样式
import { getToken } from "@/utils/auth";

//  路由白名单
const whiteList = ["/404", "/login"];
// 导航守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start(); // 开启进度条
  if (getToken()) {
    // 登陆了
    if (to.path === "login") {
      next("/");
    } else {
      // 登陆了就会去别的页面
      //  判断有没有用户资料，没有就会请求
      if (!store.getters["name"]) {
        let { roles } = await store.dispatch("user/getUserpropfileAll");
        const routes = await store.dispatch(
          "permission/filterRoutes",
          roles.menus
        );
        router.addRoutes([
          ...routes,
          { path: "*", redirect: "/404", hidden: true },
        ]);
        next(to.path);
      }else{
        next()
      }
    }
  } else {
    // 未登陆
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next("/login");
    }
  }
  NProgress.done();
})
// 后置守卫
router.afterEach(function () {
  NProgress.done(); // 关闭进度条
});
